﻿# -*- coding:utf-8 -*-
#
# склад
#
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError, AppCommand, NoArgsCommand
from django.db.models.loading import get_app, get_model


class Command( NoArgsCommand ):

    help = 'Set fild unit in part model.'
    requires_model_validation = True
    
    def handle_noargs(self, **options):
        from django.db.models import get_models
        log = []
        skiped = 0
        affected = 0 
         
        Part = get_model('sklad', 'Part')
        print u'Get model [%s] OK'% Part.__name__
        
        Waybill = get_model('sklad', 'Waybill')
        print u'Get model [%s] OK'% Waybill.__name__        
        
        part = Part.objects.all()
        for p in part:
            waybills = Waybill.objects.filter(doc='rec', part=p)
            if len(waybills) > 0:
                waybill = list(waybills)[0]
                Part.objects.filter(id=p.id).update(unit=waybill.unit)
                affected = affected + 1
                #print u'Update Part id=%s OK, Unit=%s'% (p.id, waybill.unit)
            else:
                Part.objects.filter(id=p.id).update(unit=1)
                #print u'Part id=%s never register in waybill' % p.id
                skiped = skiped + 1
        print 'Part skiped ( never register in waybill ) - %s' % skiped
        print 'Part affected - %s' % affected        
        print 'Part all - %s' %  (affected + skiped )
        
        log.append(u'Job done...')
        return "\n".join( log )
        
        
        
        